package com.yuanfeng.userms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.goods.GdsDetailsCommonQueryResultVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.userms.dto.UserFavoriteGoodsDTO;
import com.yuanfeng.userms.entity.UserFavoritesGoodsEntity;
import com.yuanfeng.userms.feign.BaseServiceClient;
import com.yuanfeng.userms.feign.GoodsServiceClient;
import com.yuanfeng.userms.mapper.UserFavoritesGoodsMapper;
import com.yuanfeng.userms.service.UserFavoritesGoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserFavoritesGoodsServiceImpl
 * @Description 收藏的商品
 * @Author cyp
 * @Date 2023-05-26 16:24:17
 * @Version 1.0
 **/
@Service
public class UserFavoritesGoodsServiceImpl extends ServiceImpl<UserFavoritesGoodsMapper, UserFavoritesGoodsEntity>
        implements UserFavoritesGoodsService {
    @Autowired
    private GoodsServiceClient goodsServiceClient;


    @Autowired
    private BaseServiceClient baseServiceClient;

    @Override
    public ResponseResult check(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        paraMap.put("userId", userInfo.getUserId());
        String torf = this.baseMapper.checkGoodsFavoriteOrNot(paraMap);
        if (null != torf) {
            return ResponseResult.success("已收藏",1);
        }
        return ResponseResult.success("未收藏",0);
    }

    @Override
    public ResponseResult add(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        paraMap.put("userId", userInfo.getUserId());
        String favoritesGoodsId =  this.baseMapper.checkGoodsFavoriteOrNot(paraMap);
        if (null != favoritesGoodsId) {
            return ResponseResult.fail(0, "重复收藏");
        }
        Integer torf = this.baseMapper.addFavoriteGoods(paraMap);
        // 更新商品的收藏量
        Map<String, String> updateMap = new HashMap<String, String>();
        updateMap.put("commonId", paraMap.get("commonId"));
        updateMap.put("goodsId", paraMap.get("goodsId"));
        updateMap.put("type", "1"); // type=1增加，2减少
        ResponseResult resultResp = goodsServiceClient.updateGoodsCollect(updateMap);
        if (1 == torf && resultResp.getCode() == 1) {
            return ResponseResult.success("增加收藏的商品成功");
        }
        return ResponseResult.fail(0, "增加收藏的商品失败");
    }

    @Override
    public ResponseResult get(Map<String, Object> paraMap) {
        try {
            String token = (String) paraMap.get("token");
            String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + token);
            paraMap.put("userId", userId);
            Map<String, Object> resultMap = new HashMap<>();

            if (null == paraMap.get("page") && null == paraMap.get("limit")) {
                return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
            }

            //将对象转换为map
            Map data = ParseMapUtils.beanToMap(paraMap);


            //分页查询数据
            IPage<UserFavoriteGoodsDTO> page = this.baseMapper.getFavoriteGoods2(new Query<UserFavoriteGoodsDTO>().getPage(data), paraMap);

            //查询是否有数据
            if (CollectionUtils.isEmpty(page.getRecords())) {
                return ResponseResult.success(BizCodeEnume.COLLECTION_IS_EMPTY.getCode(),BizCodeEnume.COLLECTION_IS_EMPTY.getMsg());
            }
            /**
             * 根据commonId查询公共信息
             *
             */
            List<UserFavoriteGoodsDTO> list = new ArrayList<>();
            for (UserFavoriteGoodsDTO userFavoriteGoods : page.getRecords()) {
                ResponseResult result = goodsServiceClient.getDetailByCommonId(userFavoriteGoods.getCommonId());
                if (!ObjectUtils.isEmpty(result.getData())) {
                    GdsDetailsCommonQueryResultVO gdsDetailsCommonQueryResult = JSON.parseObject(JSON.toJSONString(result.getData()),GdsDetailsCommonQueryResultVO.class);
                    BeanUtils.copyProperties(gdsDetailsCommonQueryResult, userFavoriteGoods);
                }
            }
            //返回数据
            return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(), BizCodeEnume.SUCCESSFULLY_QUERIED_FAVORITE_PRODUCTS.getMsg(), PageUtils.getPage(page));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult delete(Map<String, Object> paraMap) {
        String token = (String) paraMap.get("token");
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfoVO == null){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        String userId = userInfoVO.getUserId();
        paraMap.put("userId",userId );

        List<String> commonIds = (List<String>) paraMap.get("commonIds");
        if (null == commonIds) {
            return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
        }
        for (String commonId : commonIds) {

            // 调用mall库进行减收藏量
            UserFavoritesGoodsEntity entity = this.baseMapper.selectOne(new LambdaQueryWrapper<UserFavoritesGoodsEntity>()
                    .eq(UserFavoritesGoodsEntity::getCommonId, commonId)
                    .eq(UserFavoritesGoodsEntity::getUserId, userId));

            this.baseMapper.delete(new LambdaQueryWrapper<UserFavoritesGoodsEntity>()
                    .eq(UserFavoritesGoodsEntity::getCommonId, commonId)
                    .eq(UserFavoritesGoodsEntity::getUserId, userId));

            Integer goodsId = entity.getGoodsId();

            // 更新商品的收藏量
            Map<String, String> updateMap = new HashMap<String, String>();
            updateMap.put("commonId", commonId);
            updateMap.put("goodsId", goodsId.toString());
            // type=1增加，2减少
            updateMap.put("type", "2");
            ResponseResult resultResp = goodsServiceClient.updateGoodsCollect(updateMap);


        }

        return ResponseResult.success();
    }

    @Override
    public ResponseResult query(Map<String, String> paraMap) {
        Map<String, Object> map = new HashMap<>();
        map.put("favoriteGoodsCount", 0);
        map.put("favoriteShopCount", 0);
        map.put("footPrintCount", 0);
        if (null != paraMap.get("token") && "" != paraMap.get("token")) {
            String token = paraMap.get("token");
            String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + token);
            //查询收藏的商品
            List<UserFavoriteGoodsDTO> favoriteGoodsList = this.baseMapper.getFavoriteGoods(userId);
            //查询收藏的店铺
            List<Map<String,Object>> favoriteShopList = this.baseMapper.getFavoriteShops(userId);
            map.put("token", token);
            //查询游览足迹
            paraMap.put("userId",userId);
            Integer integer = this.baseMapper.selectUserFootCount(paraMap);

            if (null != favoriteGoodsList) {
                map.put("favoriteGoodsCount", favoriteGoodsList.size());
            }
            if (null != favoriteGoodsList) {
                map.put("favoriteShopCount", favoriteShopList.size());
            }
            map.put("footPrintCount", integer);
        }
        //获取广告位
        ResponseResult result = baseServiceClient.queryMePage();
        if (null != result.getData()) {
            map.put("mePageAdvertising", result.getData());
        }
        return ResponseResult.success(map);

    }


}
